package reading.web.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reading.common.enums.ErrorEnum;
import reading.common.exception.HlBadRequestException;
import reading.common.pojos.EntityResponse;
import reading.common.pojos.Success;
import reading.data.model.SysFile;
import reading.service.FileService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

import static reading.common.pojos.EntityResponse.error;
import static reading.common.pojos.EntityResponse.nullData;
import static reading.common.pojos.EntityResponse.success;

/**
 * @author TXW
 * @version V1.0
 * @Title: ${file_name}
 * @date 2018/9/17 21:49
 */
@RestController
@RequestMapping("/file")
public class FileController {
    private final FileService fileService;

    @Autowired
    public FileController(FileService fileService) {
        this.fileService = fileService;
    }

    private boolean isImage(String str) {
        final String img = "bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,wmf,webp";
        return img.contains(str);
    }

    @RequestMapping("download/{id}")
    public void download(@PathVariable Long id, HttpServletResponse response) throws IOException {
        Map map = fileService.getInputStream(id);
        SysFile f = (SysFile) map.get("f");
        InputStream inputStream = (InputStream) map.get("s");
        if (f == null || inputStream == null) {
            throw new HlBadRequestException(ErrorEnum.FILE_NOT_FIND);
        }
        if (isImage(f.getSuffixes())) {
            response.setContentType("image/jpeg");
            // 缓存一周 60*60*24*7(s)
            response.addHeader("Cache-Control","max-age=604800");
        } else {
            response.setContentType("multipart/form-data");
        }
        //2.设置文件头：最后一个参数是设置下载文件名(假如我们叫a.pdf)
        StringBuilder str = new StringBuilder("attachment;fileName=").append(new String(f.getOriginName().getBytes("utf-8"), "iso-8859-1")).append(".").append(f.getSuffixes());
        response.setHeader("Content-Disposition", str.toString());
        OutputStream outputStream = response.getOutputStream();
        byte[] b = new byte[1024];
        int n;
        while ((n = inputStream.read(b)) > 0) {
            outputStream.write(b, 0, n);
        }
        inputStream.close();
        outputStream.close();
    }

    @GetMapping("detail/{id}")
    public Success getDetail(@PathVariable Long id) {
        return Success.success(fileService.findById(id));
    }

    @GetMapping("urlEncode/{id}")
    public EntityResponse<String> urlDecode(@PathVariable Long id) {
        SysFile sysFile=fileService.findById(id);
        if(sysFile!=null){
            String path=sysFile.getPath();
            if(path==null){
                return error(ErrorEnum.DB_ERROR);
            }
            path=path.substring(17);
            try {
                path= URLEncoder.encode(path,"utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return error(ErrorEnum.DB_ERROR);
            }
            return success(path);
        }else{
            nullData();
        }
        return success();
    }


    @PostMapping("upload")
    public Map<String, Object> uploadPic(@RequestParam("upload") MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "x_requested_with");
        response.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
        SysFile resource = fileService.fileUpload(multipartFile, "1");
        return fileService.trans(resource);
    }
}
